package com.sojson.config.properties;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import com.sojson.constant.Constant;
import com.sojson.util.StringUtil;
import com.sojson.util.properties.PropertiesUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 创建PropertiesPlaceholder对象
 * 单独放到一个类是因为要初始化的有点多,而且需要设置成静态方法(最先创建,用注解的方式不能设置为静态)
 * 
 * @author liu
 * @date 2020-11-02
 */
@Slf4j
@Configuration
public class PropertiesConfig {

    /** ??? */
    private static final String SPRING_CONFIG_LOCATION = "spring.config.location";

    /**
     * 自定义配置加载，加载Properties文件，方法定义为Static的，保证优先加载
     * 
     * @return
     * @throws IOException
     */
    @Bean
    public static PropertyPlaceholderConfigurer getPropertyPlaceholderConfigurer() throws IOException {
        final PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
        ppc.setSystemPropertiesModeName("SYSTEM_PROPERTIES_MODE_OVERRIDE");
        ppc.setIgnoreResourceNotFound(true);
        if (StringUtil.isNotBlank(System.getProperty(SPRING_CONFIG_LOCATION))) {
            final List<Resource> list = new ArrayList<>();
            String configFilePath = System.getProperty(SPRING_CONFIG_LOCATION);
            String[] configFiles = configFilePath.split(",|;");

            for (String configFile : configFiles) {
                if (configFile.startsWith("file:")) {
                    list.add(new FileSystemResource(configFile));
                } else {
                    list.add(new ClassPathResource(configFile));
                }
            }
        }

        ppc.setProperties(Constant.PROPERTIES);
        ppc.setFileEncoding(PropertiesUtil.DEFAULT_ENCODING);
        log.info("PropertyPlaceholderConfigurer注入成功！");
        return ppc;
    }

}